<template>
  <view class="container">
    <!-- 头部导航 -->
    <view class="header">
      <text class="header-title">个人中心</text>
    </view>
    
    <!-- 根据用户身份动态显示内容 -->
    <view v-if="userType === 'patient'">
      <!-- 患者个人中心内容 -->
      <view class="user-info-card">
        <image class="avatar" src="/static/logo.png"></image>
        <view class="user-info">
          <text class="user-name">{{ userInfo.real_name || userInfo.wechat_name || '患者' }}</text>
          <text class="user-detail">年龄：{{ userInfo.age }} | 性别：{{ getGenderText(userInfo.gender) }}</text>
        </view>
      </view>
      
      <view class="menu-list">
        <view class="menu-item" @click="viewMyAssessments">
          <text class="menu-icon">📊</text>
          <text class="menu-text">我的评估记录</text>
          <text class="menu-arrow">→</text>
        </view>
        <view class="menu-item" @click="updatePersonalInfo">
          <text class="menu-icon">✏️</text>
          <text class="menu-text">修改个人信息</text>
          <text class="menu-arrow">→</text>
        </view>
        <view class="menu-item" @click="updatePhone">
          <text class="menu-icon">📱</text>
          <text class="menu-text">更新手机号</text>
          <text class="menu-arrow">→</text>
        </view>
        <view class="menu-item" @click="aboutUs">
          <text class="menu-icon">ℹ️</text>
          <text class="menu-text">关于我们</text>
          <text class="menu-arrow">→</text>
        </view>
      </view>
      
      <view class="stat-card">
        <view class="stat-item">
          <text class="stat-number">{{ assessmentCount }}</text>
          <text class="stat-label">已完成评估</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ healthScore }}</text>
          <text class="stat-label">健康评分</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ medicationCount }}</text>
          <text class="stat-label">用药记录</text>
        </view>
      </view>
    </view>
    
    <view v-else-if="userType === 'doctor'">
      <!-- 医生个人中心内容 -->
      <view class="user-info-card">
        <image class="avatar" src="/static/logo.png"></image>
        <view class="user-info">
          <text class="user-name">{{ getDoctorDisplayName() }}</text>
          <text class="user-detail">{{ userInfo.hospital || '未知医院' }} | {{ userInfo.department || '未知科室' }} | {{ userInfo.position || '医生' }}</text>
        </view>
      </view>
      
      <view class="menu-list">
        <view class="menu-item" @click="updatePersonalInfo">
          <text class="menu-icon">✏️</text>
          <text class="menu-text">修改个人信息</text>
          <text class="menu-arrow">→</text>
        </view>
        <view class="menu-item" @click="changePassword">
          <text class="menu-icon">🔒</text>
          <text class="menu-text">修改密码</text>
          <text class="menu-arrow">→</text>
        </view>
        <view class="menu-item" @click="notificationSettings">
          <text class="menu-icon">🔔</text>
          <text class="menu-text">通知设置</text>
          <text class="menu-arrow">→</text>
        </view>
        <view class="menu-item" @click="aboutUs">
          <text class="menu-icon">ℹ️</text>
          <text class="menu-text">关于我们</text>
          <text class="menu-arrow">→</text>
        </view>
      </view>
      
    </view>
    
    <view v-else-if="userType === 'admin'">
      <!-- 管理员个人中心内容 -->
      <view class="user-info-card">
        <image class="avatar" src="/static/logo.png"></image>
        <view class="user-info">
          <text class="user-name">{{ userInfo.realName || '管理员' }}</text>
          <text class="user-detail">系统管理员</text>
        </view>
      </view>
      
      <view class="menu-list">
        <view class="menu-item" @click="viewDoctors">
          <text class="menu-icon">👨⚕️</text>
          <text class="menu-text">医生管理</text>
          <text class="menu-arrow">→</text>
        </view>
        <view class="menu-item" @click="viewStatistics">
          <text class="menu-icon">📈</text>
          <text class="menu-text">数据统计</text>
          <text class="menu-arrow">→</text>
        </view>
        <view class="menu-item" @click="systemSettings">
          <text class="menu-icon">⚙️</text>
          <text class="menu-text">系统设置</text>
          <text class="menu-arrow">→</text>
        </view>
        <view class="menu-item" @click="aboutUs">
          <text class="menu-icon">ℹ️</text>
          <text class="menu-text">关于我们</text>
          <text class="menu-arrow">→</text>
        </view>
      </view>
      
      <view class="stat-card">
        <view class="stat-item">
          <text class="stat-number">{{ hospitalCount }}</text>
          <text class="stat-label">医院数量</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ doctorCount }}</text>
          <text class="stat-label">医生总数</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ totalAssessments }}</text>
          <text class="stat-label">总评估数</text>
        </view>
      </view>
    </view>
    
    <!-- 未登录状态 -->
    <view v-else class="not-logged-in">
      <text class="not-logged-text">请先登录</text>
      <button class="login-btn" @click="goToLogin">立即登录</button>
    </view>
    
    
    <!-- 底部退出按钮 -->
    <button class="logout-btn" @click="logout" v-if="isLoggedIn">退出登录</button>
  </view>
</template>

<script>
// 从重构后的工具层导入
import { getLoginStatus, doLogout, saveUserInfo } from '../../utils/auth.js';
import { getDoctorSelf } from '../../utils/api/doctor.js';
import { getUserInfo } from '../../utils/api/auth.js';
import { PageStackManager } from '../../utils/pageStack.js';

// 模拟数据
const mockPatientData = {
  assessmentCount: 3,
  healthScore: 85,
  medicationCount: 2
};

// 医生个人中心不再需要患者统计数据

const mockAdminData = {
  hospitalCount: 3,
  doctorCount: 25,
  totalAssessments: 156
};

export default {
  data() {
    return {
      userType: 'patient', // 默认设置为患者类型
      userInfo: {},
      isLoggedIn: false,
      assessmentCount: 0,
      healthScore: 0,
      medicationCount: 0,
      hospitalCount: 0,
      doctorCount: 0,
      totalAssessments: 0
    };
  },
  onLoad() {
    this.loadUserData();
  },
  onShow() {
    // 每次页面显示时重新检查登录状态和用户类型
    this.checkLoginStatus();
  },
  methods: {
    // 检查登录状态
    checkLoginStatus() {
      try {
        const loginStatus = getLoginStatus();
        this.isLoggedIn = loginStatus.isLoggedIn;
        
        // 确保用户类型正确设置
        if (loginStatus.userType) {
          this.userType = loginStatus.userType;
        } else {
          // 如果没有明确的用户类型，尝试从用户信息中推断
          if (this.userInfo && (this.userInfo.role === 1 || this.userInfo.user_type === 'doctor')) {
            this.userType = 'doctor';
          } else if (this.userInfo && (this.userInfo.role === 3 || this.userInfo.user_type === 'admin')) {
            this.userType = 'admin';
          } else {
            this.userType = 'patient';
          }
        }
        
        console.log('检查登录状态，用户类型:', this.userType);
      } catch (error) {
        console.error('检查登录状态失败:', error);
        // 设置默认值以防出错
        this.userType = 'patient';
      }
    },
    
    // 加载用户数据
    async loadUserData() {
      const loginStatus = getLoginStatus();
      this.isLoggedIn = loginStatus.isLoggedIn;
      
      // 确保用户类型正确设置
      if (loginStatus.userType) {
        this.userType = loginStatus.userType;
      } else if (loginStatus.userInfo) {
        if (loginStatus.userInfo.role === 1 || loginStatus.userInfo.user_type === 'doctor') {
          this.userType = 'doctor';
        } else if (loginStatus.userInfo.role === 3 || loginStatus.userInfo.user_type === 'admin') {
          this.userType = 'admin';
        } else {
          this.userType = 'patient';
        }
      }
      
      this.userInfo = loginStatus.userInfo || {};
      
      // 从API获取最新用户信息
      try {
        const response = await getUserInfo();
        
        if (response && response.code === 200 && response.data) {
          this.userInfo = response.data;
          saveUserInfo(this.userInfo);
          console.log('[个人中心] 从API获取用户信息成功:', this.userInfo);
        }
      } catch (apiError) {
        console.warn('[个人中心] 从API获取用户信息失败，使用本地缓存:', apiError);
      }
      
      // 根据用户类型加载相应的模拟数据
      if (this.userType === 'patient') {
        this.assessmentCount = mockPatientData.assessmentCount;
        this.healthScore = mockPatientData.healthScore;
        this.medicationCount = mockPatientData.medicationCount;
      } else if (this.userType === 'doctor') {
        // 医生个人中心不再显示患者统计数据
        // 尝试获取真实的医生数据
        this.getRealDoctorData();
      } else if (this.userType === 'admin') {
        this.hospitalCount = mockAdminData.hospitalCount;
        this.doctorCount = mockAdminData.doctorCount;
        this.totalAssessments = mockAdminData.totalAssessments;
      }
    },
    
    // 获取真实的医生数据
    async getRealDoctorData() {
      try {
        const res = await getDoctorSelf();
        if (res && res.data) {
          this.userInfo = { ...this.userInfo, ...res.data };
        }
      } catch (error) {
        console.error('获取医生数据失败:', error);
        // 失败时继续使用模拟数据
      }
    },
    
    // 获取医生显示名称（姓氏+医生）
    getDoctorDisplayName() {
      const fullName = this.userInfo.real_name || this.userInfo.wechat_name || '';
      if (fullName && fullName.length > 0) {
        return fullName.charAt(0) + '医生';
      }
      return '医生';
    },
    
    // 获取性别文本 - 支持字符串和数字类型
    getGenderText(gender) {
      if (gender === 'male' || gender === 1) {
        return '男';
      } else if (gender === 'female' || gender === 0) {
        return '女';
      }
      return '未知';
    },
    
    // 退出登录
    logout() {
      uni.showModal({
        title: '确认退出',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            doLogout();
          }
        }
      });
    },
    
    // 跳转到登录页面
    goToLogin() {
      uni.redirectTo({
        url: '/pages/login/login'
      });
    },
    
    // 患者功能
    viewMyAssessments() {
      uni.switchTab({
        url: '/pages/chaKanBaoGao/chaKanBaoGao'
      });
    },
    
    updatePersonalInfo() {
      uni.showToast({
        title: '修改个人信息功能待实现',
        icon: 'none'
      });
    },
    
    updatePhone() {
      uni.showToast({
        title: '更新手机号功能待实现',
        icon: 'none'
      });
    },
    
    // 医生功能
    changePassword() {
      uni.showToast({
        title: '修改密码功能待实现',
        icon: 'none'
      });
    },
    
    notificationSettings() {
      uni.showToast({
        title: '通知设置功能待实现',
        icon: 'none'
      });
    },
    
    // 管理员功能
    viewDoctors() {
      uni.showToast({
        title: '医生管理功能待实现',
        icon: 'none'
      });
    },
    
    viewStatistics() {
      uni.showToast({
        title: '数据统计功能待实现',
        icon: 'none'
      });
    },
    
    systemSettings() {
      uni.showToast({
        title: '系统设置功能待实现',
        icon: 'none'
      });
    },
    
    // 通用功能
    aboutUs() {
      uni.showToast({
        title: '关于我们功能待实现',
        icon: 'none'
      });
    },
    
  }
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.header {
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.user-info-card {
  background-color: #fff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 15rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  margin-right: 30rpx;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
  display: block;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

.user-detail {
  font-size: 28rpx;
  color: #666;
  margin-top: 10rpx;
  display: block;
  line-height: 1.4;
}

.menu-list {
  background-color: #fff;
  margin: 0 20rpx 20rpx;
  border-radius: 15rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  font-size: 40rpx;
  margin-right: 30rpx;
  width: 50rpx;
  text-align: center;
}

.menu-text {
  flex: 1;
  font-size: 32rpx;
  color: #333;
}

.menu-arrow {
  font-size: 28rpx;
  color: #ccc;
}

.stat-card {
  display: flex;
  background-color: #fff;
  margin: 0 20rpx 40rpx;
  padding: 30rpx;
  border-radius: 15rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #2db5a3;
}

.stat-label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-top: 10rpx;
}

.not-logged-in {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.not-logged-text {
  font-size: 32rpx;
  color: #666;
  margin-bottom: 40rpx;
}

.login-btn {
  width: 60%;
  background-color: #2db5a3;
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
}

.logout-btn {
  margin: 0 40rpx 40rpx;
  background-color: #f56c6c;
  color: #fff;
  border-radius: 44rpx;
  font-size: 32rpx;
}
  /* 为了确保内容不被底部导航栏遮挡 */
  .logout-btn {
    margin-bottom: 20rpx;
  }
</style>